<template>
  <div class="nav-menu">
    <el-menu
      class="el-menu-vertical-demo"
      :collapse="isCollapse"
      background-color="#0c2135"
      text-color="#b7bdc3"
      active-text-color="#0a60bd"
      :default-active="defaultValue"
    >
      <template v-for="item in userMenus" :key="item.id">
        <!-- 二级菜单 -->
        <template v-if="item.type === 1">
          <!-- 二级菜单展开 -->
          <el-sub-menu :index="item.id + ''">
            <template #title>
              <el-icon><component :is="iconComponent[item.icon]"></component></el-icon>

              <span>{{ item.name }} </span>
            </template>
            <!-- 二级菜单里面的item -->
            <template v-for="subItem in item.children" :key="subItem.id">
              <el-menu-item :index="subItem.id + ''" @click="handlerClick(subItem)">
                <span>{{ subItem.name }}</span>
              </el-menu-item>
            </template>
          </el-sub-menu>
        </template>

        <template v-else>
          <!-- 单个无法展开的菜单 -->
          <el-menu-item :index="item.id + ''" @click="handlerClick(item)">
            <span>{{ item.name }}</span>
          </el-menu-item>
        </template>
      </template>
    </el-menu>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store'
import { pathMapToMenu } from '@/utils'
import { Monitor, Setting, Goods, ChatLineRound } from '@element-plus/icons-vue'
//动态渲染icon import * as ElementIcon from "@element-plus/icons-vue"
const router = useRouter()
const route = useRoute()
interface navMenuProps {
  isCollapse: boolean
}
const props = withDefaults(defineProps<navMenuProps>(), {
  isCollapse: false
})

const iconComponent: any = {
  'el-icon-monitor': Monitor,
  'el-icon-setting': Setting,
  'el-icon-goods': Goods,
  'el-icon-chat-line-round': ChatLineRound
}
const store = useStore()
const userMenus = computed(() => store.state.login.userMenus)
const currentPath = route.path
// const currentMenu = menus(userMenus.value, currentPath)自己写的
const menu = pathMapToMenu(userMenus.value, currentPath)
const defaultValue = ref(menu.id + '')

function handlerClick(item: any) {
  router.push({
    path: item.url ?? '/not-found'
  })
}
</script>

<style lang="less" scoped>
.nav-menu {
  .el-menu {
    border-right: none;
  }
  .el-submenu {
    background-color: #001529 !important;
    // 二级菜单 ( 默认背景 )
    .el-menu-item {
      padding-left: 50px !important;
      background-color: #0c2135 !important;
    }
  }
  /deep/ .el-submenu__title {
    background-color: #001529 !important;
  }

  // hover 高亮
  .el-menu-item:hover {
    color: #fff !important; // 菜单
  }
  .el-menu-item.is-active {
    color: #fff !important;
    background-color: #0a60bd !important;
  }
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 100%;
  height: calc(100% - 48px);
}
</style>
